import json

import requests
from PyQt5.QtCore import QThread, pyqtSignal
import constant


class ImageUploaderThread(QThread):
    finished = pyqtSignal(str)  # 发送上传是否成功的信号

    def __init__(self, token, filepath, uploadType):
        super().__init__()
        self.token = token
        self.filepath = filepath
        self.uploadType = uploadType

    def run(self):
        try:
            with open(self.filepath, 'rb') as file:
                print(file)
                files = {'file': file}
                data = {'uploadType': self.uploadType}
                headers = {
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3',
                    'Accept': 'application/json',
                    #'Content-Type': 'application/json',
                    constant.X_TOKEN: self.token
                }
                response = requests.post(constant.API_HOST + '/upload/upload_image', data=data, files=files, headers=headers)
                print(response)
                if response.status_code == 200:
                    self.finished.emit(response.text)
                else:
                    self.finished.emit({'code': -1, 'message': '上传图片失败，' + response.text})

        except Exception as e:
            print(f"Error uploading file: {e}")
            self.finished.emit({'code': -1, 'message': '上传异常：' + e})
